<?php
namespace app\api\controller;

use app\admin\model\ProjectBind;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\model\User;
use fast\Random;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\Validate;

class ProjectManager extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 获取项目管理员列表
     *
     * @return void
     * @throws Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function getList()
    {
        $type = $this->request->get('type', -1);
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);

        $projectManager = new \app\admin\model\ProjectManager();
        $where = [];
        if ($type != -1) {
            $where['status'] = $type;
        }

        $query = $projectManager->where($where);
        $list = $query->page($page, $limit)->select();

        $userModel = new \app\admin\model\User();
        $projectModel = new \app\admin\model\Project();

        $userIds = array_column($list, 'uid');
        $projectIds = array_column($list, 'project_id');

        $users = $userModel->whereIn('id', $userIds)->select();
        $projects = $projectModel->whereIn('id', $projectIds)->select();

        $userMap = [];
        foreach ($users as $user) {
            $userMap[$user->id] = $user;
        }

        $projectMap = [];
        foreach ($projects as $project) {
            $projectMap[$project->id] = $project;
        }

        foreach ($list as $k => $v) {
            $list[$k]['user'] = $userMap[$v['uid']] ?? null;
            $list[$k]['project'] = $projectMap[$v['project_id']] ?? null;
            $list[$k]['total_counts'] = 0;
            $list[$k]['abnormal_counts'] = 0;
        }

        $count = $query->count();

        $data = [
            'count' => $count,
            'list' => $list
        ];

        $this->success('', $data);
    }

    /**
     * 创建项目管理员
     *
     * @return void
     * @throws DbException
     */
    public function createProjectManager()
    {
        return $this->handleProjectManagerOperation($this->request->post(), false);
    }

    /**
     * 更新项目管理员
     *
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function updateProjectManager()
    {
        return $this->handleProjectManagerOperation($this->request->post(), true);
    }

    /**
     * 处理项目管理员的创建或更新操作
     *
     * @param array $post 表单提交的数据
     * @param bool $isUpdate 是否为更新操作
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function handleProjectManagerOperation($post, $isUpdate)
    {
        $account = $post['account'];
        $field = $this->getAccountField($account);

        $existingUser = \app\admin\model\User::get([$field => $account]);
        if ($existingUser) {
            $this->handleExistingUser($existingUser);
        }

        $salt = Random::alnum();
        $password = Auth::instance()->getEncryptPassword('123456', $salt);
        $ip = request()->ip();
        $time = time();

        $userData = [
            $field => $account,
            'password' => $password,
            'nickname' => $post['nickname'],
            'salt' => $salt,
            'jointime'  => $time,
            'joinip'    => $ip,
            'logintime' => $time,
            'loginip'   => $ip,
            'prevtime'  => $time,
            'status'    => 'normal',
            'level'    => 1,
            'score'    => 0,
            'avatar'   => '',
        ];

        Db::startTrans();
        try {
            if ($isUpdate) {
                $projectManagerModel = new \app\admin\model\ProjectManager();
                $manager = $projectManagerModel->where('id', $post['id'])->find();

                if (!$manager) {
                    $this->error('项目管理员记录未找到');
                }

                $userModel = new \app\admin\model\User();
                $userUpdateResult = $userModel->save($userData, ['id' => $manager->uid]);

                if (!$userUpdateResult) {
                    throw new \Exception('用户信息更新失败');
                }
            } else {
                $userId = \app\admin\model\User::insertGetId($userData);
                if (!$userId) {
                    throw new \Exception('用户插入失败');
                }
            }

            $managerData = [
                'project_id' => $post['project_id'],
                'uid' => $isUpdate ? $manager->uid : $userId,
                'company_id' => $this->auth->id,
            ];

            $projectManagerModel = new \app\admin\model\ProjectManager();
            if ($isUpdate) {
                $managerUpdateResult = $manager->save($managerData);
                if (!$managerUpdateResult) {
                    throw new \Exception('项目管理员信息更新失败');
                }
            } else {
                $saveResult = $projectManagerModel->save($managerData);
                if (!$saveResult) {
                    throw new \Exception('项目管理员关联保存失败');
                }
            }

            Db::commit();
            $this->success($isUpdate ? '更新成功' : '创建成功');
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 处理已存在的用户
     *
     * @param \app\admin\model\User $user 已存在的用户对象
     */
    private function handleExistingUser($user)
    {
        if ($user->cate != 0) {
            $errorMessages = [
                1 => '该用户为车主',
                2 => '该用户为公司',
                3 => '该用户为司机',
                4 => '该用户为管理员'
            ];
            $message = $errorMessages[$user->cate] ?? '该用户类型未知';
            $this->error($message);
        }
        $this->error('该用户已存在');
    }

    /**
     * 根据账户信息获取账户字段
     *
     * @param string $account 账户信息
     * @return string 账户字段
     */
    private function getAccountField($account)
    {
        if (Validate::is($account, 'email')) {
            return 'email';
        } elseif (Validate::regex($account, '/^1\d{10}$/')) {
            return 'mobile';
        }
        return 'username';
    }

    /**
     * 删除项目管理员
     *
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function delete()
    {
        $id = $this->request->post('id');
        $projectManagerModel = new \app\admin\model\ProjectManager();
        $manager = $projectManagerModel->where('id', $id)->find();

        if (!$manager) {
            $this->error('项目管理员记录未找到');
        }

        Db::startTrans();
        try {
            $manager->delete();
            Db::commit();
            $this->success('删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('删除失败: ' . $e->getMessage());
        }
    }

    /**
     * 订单核销
     *
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function endOrder()
    {
        $id = $this->request->post('id');
        $orderModel = new \app\admin\model\DeliveryOrder();
        $order = $orderModel->where('id', $id)->find();

        if (!$order) {
            $this->error('订单记录未找到');
        }

        $end_img = $this->request->post('end_img');

        $data = [
            'status' => 2,
            'end_img' => $end_img,
        ];
        $res = $orderModel->save($data);
        if ($res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 获取订单核销列表
     *
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function getOrderList()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $uid = 9;
        $projectManagerModel = new \app\admin\model\ProjectManager();
        $projectIds = $projectManagerModel->where('uid', $uid)->column('project_id');
        $orderModel = new \app\admin\model\DeliveryOrder();
        $list = $orderModel->whereIn('project_id', $projectIds)->page($page, $limit)->select();
        foreach ($list as &$item) {
            $item['create_time'] = date('Y-m-d H:i:s', $item['createtime']);
            $item['project'] = (new \app\admin\model\Project())->where('id', $item['project_id'])->find();
            $item['driver'] = (new \app\admin\model\Driver())->where('id', $item['driver_id'])->find();
            $item['car'] = (new \app\admin\model\Car())->where('id', $item['car_id'])->find();
            $item['owner'] = (new \app\admin\model\Owner())->where('id', $item['owner_id'])->find();
        }
        $count = $orderModel->whereIn('project_id', $projectIds)->count();
        $this->success('获取成功', ['list' => $list, 'count' => $count]);
    }

    /**
     * 我的项目
     *
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function myProject()
    {
        $uid = $this->auth->id;
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $model = new \app\admin\model\Project();
        $projectManagerModel = new \app\admin\model\ProjectManager();
        $projectManager = $projectManagerModel->where('uid', $uid)->find();
        $list = $model->where('manager_id', $projectManager->id)->page($page, $limit)->select();
        foreach ($list as $key => $value) {
            $list[$key]['project'] = (new \app\admin\model\Project())->where('id', $value['id'])->find();
            $list[$key]['today_orders'] = 0;
            $list[$key]['today_cars'] = 0;
            $list[$key]['total_orders'] = (new \app\admin\model\DeliveryOrder())->where('project_id', $value['id'])->count();
            $list[$key]['total_cars'] = 0;
        }
        $count = $model->where('manager_id', $projectManager->id)->count();
        $data = [
            'list' => $list,
            'count' => $count
        ];
        $this->success('获取成功', $data);
    }
}
